package com.juyu.reader.pc.controller;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.juyu.reader.pc.common.Constants;
import com.juyu.reader.pc.model.Book;
import com.juyu.reader.pc.model.Order;
import com.juyu.reader.pc.model.Page;
import com.juyu.reader.pc.model.User;
import com.juyu.reader.pc.service.OrderService;
import com.juyu.reader.pc.service.UserService;
import com.juyu.reader.pc.util.DateUtil;
import com.juyu.reader.pc.util.StringUtil;

@Controller
@RequestMapping("/recharge")
public class RechargeController extends BaseController {

	Logger loger = Logger.getLogger(RechargeController.class);

	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;

	/**
	 * 充值
	 * 请求会被UserInterceptor拦截器拦截，如果没有用户登录的session，则先跳转到UserController的/user/toLogin
	 * @param request
	 * @param searchBook
	 * @param page
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView rechargeIndex(HttpServletRequest request, Book searchBook, Page page) {
		this.setNavIndex(request, 4);
		Map<String, Object> attrMap = new HashMap<String, Object>();
		return this.packModeAndView(request, "/recharge/recharge", null, attrMap);
	}

	/**
	 * payType 1支付宝
	 * 目前只有支付宝、没有微信
	 * @param request
	 * @param response
	 */
	@RequestMapping("/pay")
	public String recharegePay(HttpServletRequest request, HttpServletResponse response, Model model) {
		loger.info("支付方式payType=" + request.getParameter("payType"));
		loger.info("支付金额payAmount=" + request.getParameter("payAmount"));
		User loginUser = this.getSessionUser(request);
		int payType = Integer.valueOf(request.getParameter("payType"));
//		float payAmount = Float.valueOf(request.getParameter("payAmount"));
		float payAmount = 0.01f;

		if (payType == 1) {
			try {
				String orderNo = StringUtil.createOrderNo("AL");
				String orderName = "学而阅读PC会员充值";
				Order insertOrder = new Order();
				insertOrder.setOrderNo(orderNo);
				insertOrder.setUserId(loginUser.getUserId());
				insertOrder.setOrderName(orderName);
				insertOrder.setOrderStatus(1);// 1未支付状态
				insertOrder.setOrderAmount(payAmount);
				insertOrder.setOrderPayType(9);// 类型为支付宝，9支付宝（PC）
				insertOrder.setOrderPlatform(4);// 支付平台 ，4pc平台
				orderService.insertOrder(insertOrder);
				AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
						Constants.APP_ID, Constants.APP_PRIVATE_KEY, "json", Constants.CHARSET,
						Constants.ALIPAY_PUBLIC_KEY, "RSA2");// 获得初始化的AlipayClient
				AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
				alipayRequest.setReturnUrl(Constants.SERVICE_URL + "recharge/return");
				alipayRequest.setNotifyUrl(Constants.SERVICE_URL + "recharge/zfbNotify");// 在公共参数中设置回跳和通知地址
				alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNo + "\",\"total_amount\":" + payAmount
						+ ",\"subject\":\"" + orderName + "\",\"seller_id\":\"" + Constants.SELLER_ID
						+ "\",\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");// 填充业务参数
				String form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
				loger.info("form--------:"+form);
				response.setContentType("text/html;charset=" + Constants.CHARSET);
				response.getWriter().write(form);// 直接将完整的表单html输出到页面
				response.getWriter().flush();
				response.getWriter().close();
			} catch (Exception e) {
				loger.info(e.toString());
			}
		}

		return null;
	}

	@RequestMapping("/return")
	public ModelAndView recharegeReturn(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> paramsMap = new HashMap<String, String>();
		boolean payResult = false;
		int errorCode = 0;
		try {
			Enumeration<String> paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String paramName = paramNames.nextElement();

				String[] paramValues = request.getParameterValues(paramName);
				if (paramValues.length == 1) {
					String paramValue = paramValues[0];
					if (paramValue.length() != 0) {
						paramsMap.put(paramName, paramValue);
					}
				}
			}
			Set<Map.Entry<String, String>> set = paramsMap.entrySet();
			loger.info("alipay return------------------------------");
			for (Map.Entry<String, String> entry : set) {
				loger.info(entry.getKey() + ":" + entry.getValue());
			}
			loger.info("alipay return------------------------------");
			boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, Constants.ALIPAY_PUBLIC_KEY, Constants.CHARSET,
					"RSA2"); // 调用SDK验证签名
			if (signVerified) {
				loger.info("同步通知=return签名验证成功！");
				// 同步return不做逻辑处理，只提示充值成功
				payResult = true;
				errorCode = 0;
			} else {
				loger.info("同步通知=return签名验证失败！");
				payResult = false;
				errorCode = -1;
			}
		} catch (Exception e) {
			loger.info("alipay return error=" + e.toString());
			payResult = false;
			errorCode = -2;
		}
		if (payResult) {
			return this.packModeAndView(request, "/recharge/rechargeReturn", "支付完成，请点击个人中心-充值记录查看订单支付状态！", null);
		} else {
			return this.packModeAndView(request, "/common/error", "支付异常（" + errorCode + "）！", null);
		}

	}

	@RequestMapping("/zfbNotify")
	@ResponseBody
	public String recharegeNofity(HttpServletRequest request, HttpServletResponse response) {
		// success注意返回字符串
		loger.info("zfb 同步开始------------------------------");
		try {
	        // 获取支付宝POST过来反馈信息
	        Map<String, String> params = new HashMap<String, String>();
	        Map<String, String[]> requestParams = request.getParameterMap();
	        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
	            String name = iter.next();
	            String[] values = requestParams.get(name);
	            String valueStr = "";
	            for (int i = 0; i < values.length; i++) {
	                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
	            }
	            // 乱码解决，这段代码在出现乱码时使用。
	            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
	            params.put(name, valueStr);
	        }

//			Set<Map.Entry<String, String>> set = params.entrySet();
//			loger.info("pay notify------------------------------");
//			for (Map.Entry<String, String> entry : set) {
//				loger.info(entry.getKey() + ":" + entry.getValue());
//			}
//			loger.info("pay notify------------------------------");
	        boolean flag = AlipaySignature.rsaCheckV1(params,Constants.ALIPAY_PUBLIC_KEY,"utf-8","RSA2");
			if (flag) {
				// TODO
				// 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
				loger.info("异步通知=notify签名验证成功！");
				// 是否已经被处理
				Order findOrder = new Order();
				findOrder.setOrderNo(params.get("out_trade_no"));
				List<Order> orderList = orderService.findOrderByNo(findOrder);
				if (orderList.size() == 1) {
					Order order = orderList.get(0);
					if (order.getOrderDeal() == 1) {
						loger.info("异步通知=notify订单=" + order.getOrderNo() + "已经被处理！");
					} else {
						if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
							if (order.getOrderAmount() != Float.valueOf(params.get("total_amount"))
									|| !Constants.APP_ID.equals(params.get("app_id"))
									|| !Constants.SELLER_ID.equals(params.get("seller_id"))) {
								loger.info("异步通知=notify订单=" + order.getOrderNo() + "参数验证不一致！");
							} else {
								// 支付成功
								Order updateOrder = new Order();
								updateOrder.setOrderNo(order.getOrderNo());
								updateOrder.setOrderStatus(2);// 订单状态，-1订单过期，0默认，1未支付，2支付成功
								updateOrder.setOrderTradeNo(params.get("trade_no"));
								updateOrder.setNotifyId(params.get("notify_id"));
								updateOrder.setNotifyTime(DateUtil.pareDate(params.get("notify_time")));
								updateOrder.setBuyerId(params.get("buyer_id"));
								updateOrder.setSellerId(params.get("seller_id"));
								updateOrder.setOrderDeal(1);// 标记为已经处理
								int updateResult = orderService.updateOrder(updateOrder);
								if (updateResult == 1) {
									// 充值成功后，处理逻辑，更新用户书币（如果并发量过大可以这里添加消息中间件）
									userService.updateUserGold(order);
								} else {
									loger.info("异步通知=notify获取并验证成功，但本地更新订单状态失败！");
									return "error";
								}
							}
						} else {
							loger.info("异步通知=notify订单=" + order.getOrderNo() + "支付失败！trade_status="
									+ params.get("trade_status"));
						}
					}
				} else {
					loger.info("订单编号=" + findOrder.getOrderNo() + "不存在！");
				}
			} else {
				// TODO 验签失败则记录异常日志，并在response中返回failure.
				loger.info("异步通知=notify签名验证失败！");
				return "error";
			}
		} catch (Exception e) {
			loger.info("alipay notify error=" + e.toString());
			return "error";
		}
		return "success";
	}

	// @RequestMapping("/nowreturn")
	// public ModelAndView recharegeNowPayReturn(HttpServletRequest request,
	// HttpServletResponse response) {
	// Map<String, String> paramsMap = new HashMap<String, String>();
	// boolean payResult = false;
	// int errorCode = 0;
	// try {
	// Enumeration<String> paramNames = request.getParameterNames();
	// while (paramNames.hasMoreElements()) {
	// String paramName = paramNames.nextElement();
	//
	// String[] paramValues = request.getParameterValues(paramName);
	// if (paramValues.length == 1) {
	// String paramValue = paramValues[0];
	// if (paramValue.length() != 0) {
	// paramsMap.put(paramName, paramValue);
	// }
	// }
	// }
	// Set<Map.Entry<String, String>> set = paramsMap.entrySet();
	// loger.info("nowpay return------------------------------");
	// for (Map.Entry<String, String> entry : set) {
	// loger.info(entry.getKey() + ":" + entry.getValue());
	// }
	// loger.info("nowpay return------------------------------");
	// // 现在支付同步通知，结果md5签名验证，暂时不调用
	//
	// payResult = true;
	// errorCode = 0;
	//
	// } catch (Exception e) {
	// loger.info("nowpay return error=" + e.toString());
	// payResult = false;
	// errorCode = -2;
	// }
	// if (payResult) {
	// return this.packModeAndView(request, "/recharge/rechargeReturn",
	// "支付完成，请点击个人中心-充值记录查看订单支付状态！", null);
	// } else {
	// return this.packModeAndView(request, "/book/error", "支付异常（" + errorCode +
	// "）！", null);
	// }
	//
	// }
	//
	// @RequestMapping("/nownotify")
	// @ResponseBody
	// public String recharegeNowPayNofity(HttpServletRequest request,
	// HttpServletResponse response) {
	// try {
	//
	// loger.info("nowpay notify------------------------------");
	// // 获取通知数据需要从body中流式读取
	// BufferedReader reader = request.getReader();
	// StringBuilder reportBuilder = new StringBuilder();
	// String tempStr = "";
	// while ((tempStr = reader.readLine()) != null) {
	// reportBuilder.append(tempStr);
	// }
	// // 报文数据字符串
	// String reportContent = reportBuilder.toString();
	// loger.info("nowpay notify data=" + reportContent);
	// loger.info("nowpay notify------------------------------");
	// // String
	// //
	// tempdata="appId=1478052181967614&channelOrderNo=4008562001201611028511962847&deviceType=06&funcode=N001&mhtCharset=UTF-8&mhtCurrencyType=156&mhtOrderAmt=1&mhtOrderName=%E4%B9%A6%E9%A6%99%E9%98%85%E8%AF%BB%E4%BC%9A%E5%91%98%E5%85%85%E5%80%BC&mhtOrderNo=NWX201611021728096365682&mhtOrderStartTime=20161102172809&mhtOrderTimeOut=3600&mhtOrderType=01&nowPayOrderNo=200601201611021728093747913&payChannelType=13&signType=MD5&signature=0e95bf45250a73256f1d79aa506b096a&tradeStatus=A001";
	// Map<String, String> dataMap =
	// NowPayReportConvertor.parseFormDataPatternReportWithDecode(reportContent,
	// "UTF-8", "UTF-8");
	//
	// // 去除签名类型和签名值
	// dataMap.remove("signType");
	// String signature = dataMap.remove("signature");
	// String localSignature = Md5Util.signNowpayDataMD5(dataMap,
	// Constants.NOW_APP_PRIVATE_KEY);
	// // 验证签名
	// boolean isValidSignature = localSignature.equals(signature);
	// if (isValidSignature) {
	// loger.info("异步通知=notify签名验证成功！");
	// // 是否已经被处理
	// Order findOrder = new Order();
	// findOrder.setOrderNo(dataMap.get("mhtOrderNo"));
	// List<Order> orderList = orderService.findOrderByNo(findOrder);
	// if (orderList.size() == 1) {
	// Order order = orderList.get(0);
	// if (order.getOrderDeal() == 1) {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "已经被处理！");
	// } else {
	// if ("A001".equals(dataMap.get("tradeStatus"))) {
	//
	// // 支付成功
	// Order updateOrder = new Order();
	// updateOrder.setOrderNo(order.getOrderNo());
	// updateOrder.setOrderStatus(2);// 订单状态，-1订单过期，0默认，1未支付，2支付成功
	// updateOrder.setOrderTradeNo(dataMap.get("nowPayOrderNo"));
	// updateOrder.setNotifyId(null);
	// updateOrder.setNotifyTime(new Date());
	// updateOrder.setBuyerId(null);
	// updateOrder.setSellerId(dataMap.get("appId"));
	// updateOrder.setOrderDeal(1);// 标记为已经处理
	// int updateResult = orderService.updateOrder(updateOrder);
	// if (updateResult == 1) {
	// // 充值成功后，处理逻辑，更新用户书币（如果并发量过大可以这里添加消息中间件）
	// userService.updateUserGold(order);
	// } else {
	// loger.info("异步通知=notify获取并验证成功，但本地更新订单状态失败！");
	// return "error";
	// }
	//
	// } else {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "支付失败！trade_status="
	// + dataMap.get("trade_status"));
	// }
	// }
	// } else {
	// loger.info("订单编号=" + findOrder.getOrderNo() + "不存在！");
	// }
	// response.getOutputStream().write("success=Y".getBytes());
	// } else {
	// loger.info("异步通知=notify签名验证失败！");
	// response.getOutputStream().write("success=N".getBytes());
	// }
	// } catch (Exception e) {
	// loger.info("nowpay notify error=" + e.toString());
	// return "error";
	// }
	// return "success";
	// }
	//
	// @RequestMapping("/nowsmreturn")
	// public ModelAndView recharegeNowsmPayReturn(HttpServletRequest request,
	// HttpServletResponse response) {
	// Map<String, String> paramsMap = new HashMap<String, String>();
	// boolean payResult = false;
	// int errorCode = 0;
	// try {
	// Enumeration<String> paramNames = request.getParameterNames();
	// while (paramNames.hasMoreElements()) {
	// String paramName = paramNames.nextElement();
	//
	// String[] paramValues = request.getParameterValues(paramName);
	// if (paramValues.length == 1) {
	// String paramValue = paramValues[0];
	// if (paramValue.length() != 0) {
	// paramsMap.put(paramName, paramValue);
	// }
	// }
	// }
	// Set<Map.Entry<String, String>> set = paramsMap.entrySet();
	// loger.info("nowsmpay return------------------------------");
	// for (Map.Entry<String, String> entry : set) {
	// loger.info(entry.getKey() + ":" + entry.getValue());
	// }
	// loger.info("nowsmpay return------------------------------");
	// // 现在支付同步通知，结果md5签名验证，暂时不调用
	//
	// payResult = true;
	// errorCode = 0;
	//
	// } catch (Exception e) {
	// loger.info("nowsmpay return error=" + e.toString());
	// payResult = false;
	// errorCode = -2;
	// }
	// if (payResult) {
	// return this.packModeAndView(request, "/recharge/rechargeReturn",
	// "支付完成，请点击个人中心-充值记录查看订单支付状态！", null);
	// } else {
	// return this.packModeAndView(request, "/book/error", "支付异常（" + errorCode +
	// "）！", null);
	// }
	//
	// }
	//
	// @RequestMapping("/nowsmnotify")
	// @ResponseBody
	// public String recharegeNowsmPayNofity(HttpServletRequest request,
	// HttpServletResponse response) {
	// try {
	//
	// loger.info("nowsmpay notify------------------------------");
	// // 获取通知数据需要从body中流式读取
	// BufferedReader reader = request.getReader();
	// StringBuilder reportBuilder = new StringBuilder();
	// String tempStr = "";
	// while ((tempStr = reader.readLine()) != null) {
	// reportBuilder.append(tempStr);
	// }
	// // 报文数据字符串
	// String reportContent = reportBuilder.toString();
	// loger.info("nowsmpay notify data=" + reportContent);
	// loger.info("nowsmpay notify------------------------------");
	// // String
	// //
	// tempdata="appId=1478052181967614&channelOrderNo=4008562001201611028511962847&deviceType=06&funcode=N001&mhtCharset=UTF-8&mhtCurrencyType=156&mhtOrderAmt=1&mhtOrderName=%E4%B9%A6%E9%A6%99%E9%98%85%E8%AF%BB%E4%BC%9A%E5%91%98%E5%85%85%E5%80%BC&mhtOrderNo=NWX201611021728096365682&mhtOrderStartTime=20161102172809&mhtOrderTimeOut=3600&mhtOrderType=01&nowPayOrderNo=200601201611021728093747913&payChannelType=13&signType=MD5&signature=0e95bf45250a73256f1d79aa506b096a&tradeStatus=A001";
	// Map<String, String> dataMap =
	// NowPayReportConvertor.parseFormDataPatternReportWithDecode(reportContent,
	// "UTF-8", "UTF-8");
	//
	// // 去除签名类型和签名值
	// dataMap.remove("signType");
	// String signature = dataMap.remove("signature");
	// String localSignature = Md5Util.signNowpayDataMD5(dataMap,
	// Constants.NOW_SM_APP_PRIVATE_KEY);
	// // 验证签名
	// boolean isValidSignature = localSignature.equals(signature);
	// if (isValidSignature) {
	// loger.info("异步通知=notify签名验证成功！");
	// // 是否已经被处理
	// Order findOrder = new Order();
	// findOrder.setOrderNo(dataMap.get("mhtOrderNo"));
	// List<Order> orderList = orderService.findOrderByNo(findOrder);
	// if (orderList.size() == 1) {
	// Order order = orderList.get(0);
	// if (order.getOrderDeal() == 1) {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "已经被处理！");
	// } else {
	// if ("A001".equals(dataMap.get("tradeStatus"))) {
	//
	// // 支付成功
	// Order updateOrder = new Order();
	// updateOrder.setOrderNo(order.getOrderNo());
	// updateOrder.setOrderStatus(2);// 订单状态，-1订单过期，0默认，1未支付，2支付成功
	// updateOrder.setOrderTradeNo(dataMap.get("nowPayOrderNo"));
	// updateOrder.setNotifyId(null);
	// updateOrder.setNotifyTime(new Date());
	// updateOrder.setBuyerId(null);
	// updateOrder.setSellerId(dataMap.get("appId"));
	// updateOrder.setOrderDeal(1);// 标记为已经处理
	// int updateResult = orderService.updateOrder(updateOrder);
	// if (updateResult == 1) {
	// // 充值成功后，处理逻辑，更新用户书币（如果并发量过大可以这里添加消息中间件）
	// userService.updateUserGold(order);
	// } else {
	// loger.info("异步通知=notify获取并验证成功，但本地更新订单状态失败！");
	// return "error";
	// }
	//
	// } else {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "支付失败！trade_status="
	// + dataMap.get("trade_status"));
	// }
	// }
	// } else {
	// loger.info("订单编号=" + findOrder.getOrderNo() + "不存在！");
	// }
	// response.getOutputStream().write("success=Y".getBytes());
	// } else {
	// loger.info("异步通知=notify签名验证失败！");
	// response.getOutputStream().write("success=N".getBytes());
	// }
	// } catch (Exception e) {
	// loger.info("nowsmpay notify error=" + e.toString());
	// return "error";
	// }
	// return "success";
	// }
	//
	// @RequestMapping("/nowgzhreturn")
	// public ModelAndView recharegeNowgzhPayReturn(HttpServletRequest request,
	// HttpServletResponse response) {
	// Map<String, String> paramsMap = new HashMap<String, String>();
	// boolean payResult = false;
	// int errorCode = 0;
	// try {
	// Enumeration<String> paramNames = request.getParameterNames();
	// while (paramNames.hasMoreElements()) {
	// String paramName = paramNames.nextElement();
	//
	// String[] paramValues = request.getParameterValues(paramName);
	// if (paramValues.length == 1) {
	// String paramValue = paramValues[0];
	// if (paramValue.length() != 0) {
	// paramsMap.put(paramName, paramValue);
	// }
	// }
	// }
	// Set<Map.Entry<String, String>> set = paramsMap.entrySet();
	// loger.info("nowgzhpay return------------------------------");
	// for (Map.Entry<String, String> entry : set) {
	// loger.info(entry.getKey() + ":" + entry.getValue());
	// }
	// loger.info("nowgzhpay return------------------------------");
	// // 现在支付同步通知，结果md5签名验证，暂时不调用
	//
	// payResult = true;
	// errorCode = 0;
	//
	// } catch (Exception e) {
	// loger.info("nowsmpay return error=" + e.toString());
	// payResult = false;
	// errorCode = -2;
	// }
	// if (payResult) {
	// return this.packModeAndView(request, "/recharge/rechargeReturn",
	// "支付完成，请点击个人中心-充值记录查看订单支付状态！", null);
	// } else {
	// return this.packModeAndView(request, "/book/error", "支付异常（" + errorCode +
	// "）！", null);
	// }
	//
	// }
	//
	// @RequestMapping("/nowgzhnotify")
	// @ResponseBody
	// public String recharegeNowgzhPayNofity(HttpServletRequest request,
	// HttpServletResponse response) {
	// try {
	//
	// loger.info("nowgzhpay notify------------------------------");
	// // 获取通知数据需要从body中流式读取
	// BufferedReader reader = request.getReader();
	// StringBuilder reportBuilder = new StringBuilder();
	// String tempStr = "";
	// while ((tempStr = reader.readLine()) != null) {
	// reportBuilder.append(tempStr);
	// }
	// // 报文数据字符串
	// String reportContent = reportBuilder.toString();
	// loger.info("nowgzhpay notify data=" + reportContent);
	// loger.info("nowgzhpay notify------------------------------");
	// // String
	// //
	// tempdata="appId=1478052181967614&channelOrderNo=4008562001201611028511962847&deviceType=06&funcode=N001&mhtCharset=UTF-8&mhtCurrencyType=156&mhtOrderAmt=1&mhtOrderName=%E4%B9%A6%E9%A6%99%E9%98%85%E8%AF%BB%E4%BC%9A%E5%91%98%E5%85%85%E5%80%BC&mhtOrderNo=NWX201611021728096365682&mhtOrderStartTime=20161102172809&mhtOrderTimeOut=3600&mhtOrderType=01&nowPayOrderNo=200601201611021728093747913&payChannelType=13&signType=MD5&signature=0e95bf45250a73256f1d79aa506b096a&tradeStatus=A001";
	// Map<String, String> dataMap =
	// NowPayReportConvertor.parseFormDataPatternReportWithDecode(reportContent,
	// "UTF-8", "UTF-8");
	//
	// // 去除签名类型和签名值
	// dataMap.remove("signType");
	// String signature = dataMap.remove("signature");
	// String localSignature = Md5Util.signNowpayDataMD5(dataMap,
	// Constants.NOW_GZH_APP_PRIVATE_KEY);
	// // 验证签名
	// boolean isValidSignature = localSignature.equals(signature);
	// if (isValidSignature) {
	// loger.info("异步通知=notify签名验证成功！");
	// // 是否已经被处理
	// Order findOrder = new Order();
	// findOrder.setOrderNo(dataMap.get("mhtOrderNo"));
	// List<Order> orderList = orderService.findOrderByNo(findOrder);
	// if (orderList.size() == 1) {
	// Order order = orderList.get(0);
	// if (order.getOrderDeal() == 1) {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "已经被处理！");
	// } else {
	// if ("A001".equals(dataMap.get("tradeStatus"))) {
	//
	// // 支付成功
	// Order updateOrder = new Order();
	// updateOrder.setOrderNo(order.getOrderNo());
	// updateOrder.setOrderStatus(2);// 订单状态，-1订单过期，0默认，1未支付，2支付成功
	// updateOrder.setOrderTradeNo(dataMap.get("nowPayOrderNo"));
	// updateOrder.setNotifyId(null);
	// updateOrder.setNotifyTime(new Date());
	// updateOrder.setBuyerId(null);
	// updateOrder.setSellerId(dataMap.get("appId"));
	// updateOrder.setOrderDeal(1);// 标记为已经处理
	// int updateResult = orderService.updateOrder(updateOrder);
	// if (updateResult == 1) {
	// // 充值成功后，处理逻辑，更新用户书币（如果并发量过大可以这里添加消息中间件）
	// userService.updateUserGold(order);
	// } else {
	// loger.info("异步通知=notify获取并验证成功，但本地更新订单状态失败！");
	// return "error";
	// }
	//
	// } else {
	// loger.info("异步通知=notify订单=" + order.getOrderNo() + "支付失败！trade_status="
	// + dataMap.get("trade_status"));
	// }
	// }
	// } else {
	// loger.info("订单编号=" + findOrder.getOrderNo() + "不存在！");
	// }
	// response.getOutputStream().write("success=Y".getBytes());
	// } else {
	// loger.info("异步通知=notify签名验证失败！");
	// response.getOutputStream().write("success=N".getBytes());
	// }
	// } catch (Exception e) {
	// loger.info("nowgzhpay notify error=" + e.toString());
	// return "error";
	// }
	// return "success";
	// }
	//
	// @RequestMapping("/qpaynotify")
	// @ResponseBody
	// public String recharegeQPayNofity(HttpServletRequest request,
	// HttpServletResponse response) {
	//
	// loger.info("QQ钱包支付回调==========>");
	// StringBuffer jb = new StringBuffer();
	// String line = null;
	// try {
	// BufferedReader reader = request.getReader();
	// while ((line = reader.readLine()) != null) {
	// jb.append(line);
	// }
	// loger.info("QQ钱包支付回调xml=" + jb.toString());
	// Map<String, String> notifyMap = this.parseXml(jb.toString());
	// String tradeState = notifyMap.get("trade_state");
	// if (tradeState != null && tradeState.toUpperCase().equals("SUCCESS")) {
	// // 验证签名
	// String formSign = notifyMap.get("sign");
	// notifyMap.remove("sign");
	// String valiSign = this.createSign(notifyMap);
	// if (valiSign.equals(formSign)) {
	// String appId = notifyMap.get("appid");
	// String mchId = notifyMap.get("mch_id");
	// String outTradeNo = notifyMap.get("out_trade_no");
	// String timeEnd = notifyMap.get("time_end");// 支付完成时间
	// String totalFee = notifyMap.get("total_fee");// 订单金额
	// String transactionId = notifyMap.get("transaction_id");// QQ钱包订单号
	// loger.info("QQ钱包支付回调：支付结果成功");
	//
	// // 是否已经被处理
	// Order findOrder = new Order();
	// findOrder.setOrderNo(outTradeNo);
	// List<Order> orderList = orderService.findOrderByNo(findOrder);
	// if (orderList.size() == 1) {
	// Order order = orderList.get(0);
	// if (order.getOrderDeal() == 1) {
	// loger.info("QQ钱包支付回调：订单=" + order.getOrderNo() + "已经被处理！");
	// } else {
	// Order updateOrder = new Order();
	// updateOrder.setOrderNo(order.getOrderNo());
	// updateOrder.setOrderStatus(2);// 订单状态，-1订单过期，0默认，1未支付，2支付成功
	// updateOrder.setOrderTradeNo(transactionId);
	// updateOrder.setNotifyId(null);
	// updateOrder.setNotifyTime(new Date());
	// updateOrder.setBuyerId(null);
	// updateOrder.setSellerId(appId);
	// updateOrder.setOrderDeal(1);// 标记为已经处理
	// int updateResult = orderService.updateOrder(updateOrder);
	// if (updateResult == 1) {
	// // 充值成功后，处理逻辑，更新用户书币（如果并发量过大可以这里添加消息中间件）
	// userService.updateUserGold(order);
	// } else {
	// loger.info("QQ钱包支付回调：获取并验证成功，但本地更新订单状态失败！");
	// }
	// }
	// } else {
	// loger.info("QQ钱包支付订单编号=" + findOrder.getOrderNo() + "不存在！");
	// }
	// Map<String, String> resultMap = new HashMap<String, String>();
	// resultMap.put("return_code", "SUCCESS");// SUCCESS/FAIL
	// resultMap.put("return_msg", "OK");
	// String resultString = this.returnInfoToXML(resultMap);
	// loger.info("QQ钱包支付返回xml="+resultString);
	// loger.info("QQ钱包支付回调==========<");
	// return resultString;
	//
	// } else {
	// loger.info("QQ钱包支付回调：签名验证失败");
	// }
	// } else {
	// loger.info("QQ钱包支付回调：支付结果失败");
	// }
	// } catch (Exception e) {
	// loger.info("QQ钱包支付回调处理错误=" + e.toString());
	// }
	// Map<String, String> resultMap = new HashMap<String, String>();
	// resultMap.put("return_code", "FAIL");// SUCCESS/FAIL
	// resultMap.put("return_msg", "ERROR");
	// String resultString = this.returnInfoToXML(resultMap);
	// loger.info("QQ钱包支付回调==========<");
	// return resultString;
	// }
	//
	// private Map<String, String> createPayInfo(Order order, HttpServletRequest
	// request) {
	// Map<String, String> dataMap = new HashMap<String, String>();
	// dataMap.put("appid", Constants.QP_APP_ID);
	// dataMap.put("device_info", "WEB");
	// dataMap.put("mch_id", Constants.QP_MCH_ID);
	// dataMap.put("nonce_str", StringUtil.createNumberUUID());
	// dataMap.put("body", order.getOrderName());
	// dataMap.put("attach", "");
	// dataMap.put("out_trade_no", order.getOrderNo());
	// dataMap.put("fee_type", "CNY");
	// int totalFee=((int)order.getOrderAmount())*100;
	// dataMap.put("total_fee", String.valueOf(totalFee));
	// dataMap.put("spbill_create_ip", NetUtil.getIpAddress(request));
	// dataMap.put("notify_url", "http://m.juzibook.com/recharge/qpaynotify");
	// dataMap.put("trade_type", "NATIVE");
	// return dataMap;
	// }
	//
	// // private Map<String, String> createH5Info(String prepayId) {
	// // Map<String, String> dataMap = new HashMap<String, String>();
	// // dataMap.put("appId", Constants.APP_ID);
	// // dataMap.put("timeStamp", DateUtil.getTimeStamp());
	// // dataMap.put("nonceStr", StringUtil.createNumberUUID());
	// // dataMap.put("package", "prepay_id=" + prepayId);
	// // dataMap.put("signType", "MD5");
	// // return dataMap;
	// // }
	//
	// private String createSign(Map<String, String> dataMap) {
	// String signed = Md5Util.signQPayDataMD5(dataMap, Constants.QP_MCH_KEY);
	// return signed;
	// }
	//
	// private String payInfoToXML(Map<String, String> map) {
	// Document document = DocumentHelper.createDocument();
	// Element root = document.addElement("xml");
	//
	// if (map != null) {
	//
	// Iterator<String> it = map.keySet().iterator();
	// while (it.hasNext()) {
	// String key = (String) it.next();
	// Element param = root.addElement(key);
	// Object obj = map.get(key);
	// if (obj != null) {
	// if (obj instanceof java.lang.Integer) {
	// param.addText(String.valueOf(obj));
	// } else {
	// // param.addCDATA((String) obj);
	// param.addText((String) obj);
	// }
	// }
	// }
	// }
	// return document.asXML();
	// }
	//
	// private String returnInfoToXML(Map<String, String> map) {
	// Document document = DocumentHelper.createDocument();
	// Element root = document.addElement("xml");
	// if (map != null) {
	// Iterator<String> it = map.keySet().iterator();
	// while (it.hasNext()) {
	// String key = (String) it.next();
	// Element param = root.addElement(key);
	// String value = map.get(key);
	// if (value != null) {
	// param.addCDATA(value);
	// }
	// }
	// }
	// return document.asXML();
	// }
	//
	// private Map<String, String> parseXml(String xml) throws Exception {
	// Map<String, String> map = new HashMap<String, String>();
	// Document document = DocumentHelper.parseText(xml);
	// Element root = document.getRootElement();
	// List<Element> elementList = root.elements();
	// for (Element e : elementList) {
	// map.put(e.getName(), e.getText());
	// }
	// return map;
	// }
}
